#include"Acceptor.h"

Acceptor::Acceptor(EventLoop *loop, const std::string &ip, const uint16_t port):loop_(loop)
{
    // 创建服务端的地址
    InetAddress servaddr(ip, port);
    // 创建服务端的socket
    servsock_ = new Socket(createnoblocingfd());
    servsock_->setreuseaddr(true);
    servsock_->settcpnodelay(true);
    servsock_->bind(servaddr);
    servsock_->listen();

    // 让 epoll 监视 fd 的读事件，采用水平触发
    acceptchannel_ = new Channel(loop_, servsock_->fd());
    // 设置listenfd的读事件回调函数
    acceptchannel_->setreadcallback(std::bind(&Acceptor::newconnection, this));
    acceptchannel_->enablereading();
}

Acceptor::~Acceptor()
{
    delete servsock_;
    delete acceptchannel_;
}

void Acceptor::newconnection()
{
    // 客户端的地址
    InetAddress clientaddr;
    Socket *clientsock = new Socket(servsock_->accept(clientaddr));
    // 保存地址信息
    clientsock->setaddress(clientaddr);
    
    newconnectioncb_(clientsock);
}

void Acceptor::setnewconnectioncb(std::function<void(Socket *)> fn)
{
    newconnectioncb_ = fn;
}
